<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 首页控制器
// +----------------------------------------------------------------------

namespace app\home\controller;

use app\common\model\Article;
use app\common\model\ArticleCategory;
use app\common\model\Comment;
use think\facade\Request;
use think\facade\View;

class IndexController extends HomeBaseController
{
    // 首页
    public function index()
    {
        //$pay = new Sumpay();

        //$aes_key = "F3EmeNDxNEdXzTPHfOC3ZS3SB27kE7oRlHFRdF9CvzdaKczV3P/hKTqMWW0dHz6XCdgSKSZOd8qB05ezsc2Q7C6tKRg9rq/HGKyk3t5tLdOFZ3nB1Ra5XWxvYqfas7gCUi3fi4FPUHa6ARKvQ5iRpwmNOndymfZVYHmwL4d1gHN2x42XMqdP5GPbosG8SQR7S/KsxdT9Ay3CXG80Qh8fSsIZZt5QhVDRHih82//ru1n+VN3t55IN82X1rtjVqlkku9gTgdtJwqg3VBBmwmHRQ1mfZ69sW2LeaUKqu0TBrvsg9Kd01d1Q7Fs0/cZQUwFgDhRb3tNuEyJomJObqhJw2A==";
        //halt(openssl_get_cipher_methods());

        //$data = "6217231303001013864";
       // $data = base64_encode(openssl_encrypt($data, "AES-256-CBC", "sumpay", OPENSSL_RAW_DATA));
        //echo $data;

        //$data = "xRRQm48Xdl2haaGXjT5+VQ==";
        //echo openssl_decrypt(base64_decode($data), "AES-256-CBC", $aes_key, OPENSSL_RAW_DATA);

        //echo openssl_decrypt(base64_decode("xRRQm48Xdl2haaGXjT5+VQ=="), 'AES-128-ECB', "");

        //die;
        //halt($pay->avaliableBank());
        //halt($pay->remove('150508564162'));
        return View::fetch('index/index');
    }

    /**
     * 证书解密字符串
     * @param string $data 签名数据
     * @param string $publicPath 公钥证书路径
     * @param string $password 证书密码
     * @param string $signature
     * @return false|int
     */
    function verify(string $data, string $publicPath, string $password, string $signature)
    {
        $certs = array();
        openssl_pkcs12_read(file_get_contents($publicPath), $certs, $password);
        if (!$certs) {
            return -1;
        }
        // openssl_verify验签成功返回1，失败0，错误返回-1
        return openssl_verify($data, base64_decode($signature), $certs['cert']);
    }


    public function demo()
    {
        return View::fetch('index/demo');
    }

    // 搜索
    public function search(){
        $search = Request::param('search');//关键字
        if(empty($search)){
            $this->error('请输入关键词');
        }
        return View::fetch('index/search.html');
    }

    // 标签
    public function tag(){
        $tag = Request::param('t');
        if(empty($tag)){
            $this->error('请输入关键词');
        }
        $view = [
            'tag'         => $tag,
        ];
        View::assign($view);
        return View::fetch('index/tag.html');
    }

    /**
     * 显示资源列表
     *
     * @return string
     */
    public function forum()
    {
        $request = $this->request->param();
        $where = [];
        if (!empty($request['category_id'])) {
            $where[] = ['category_id', '=', $request['category_id']];
        }
        if (isset($request['keywords'])) {
            $where[] = ['title', 'like', '%' . $request['keywords'] . '%'];
        }
        $sort = isset($request['sort']) && $request['sort'] == 'hot' ? 'comment_count' : 'id';

        $list = Article::with([
            'category' => function($query) {
                $query->field('id,name');
            },
            'user'=> function($query) {
                $query->field('id,username,avatar');
            }
        ])->field('id,category_id,user_id,title,read_count,comment_count,score,stick,digest,create_time,update_time')
            ->where($where)
            ->order($sort . ' desc')
            ->paginate([
                'list_rows' => 10,
                'query'     => $request
            ]);
        View::assign([
            'list' => $list,
            'page' => $list->render()
        ]);
        return View::fetch('forum/list');
    }

    /**
     * 显示创建资源表单页.
     *
     * @return string|\think\response\Redirect
     */
    public function forum_create()
    {
        if (!auth()->check()) {
            return redirect('/login');
        }

        View::assign([
            'categories' => ArticleCategory::categories(),
            'article'    => []
        ]);
        return View::fetch('forum/form');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return string
     */
    public function read($id)
    {
        $article = Article::find($id);
        if (!$article) {
            return View::fetch('index/404');
        }

        // 更新点击数
        Article::where('id', $id)->inc('read_count')->update();
        View::assign([
            'article'    => $article,
            'comments'   => Comment::with('user')->where('commentable_id', $id)->select()
        ]);
        return View::fetch('forum/show');
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function forum_edit($id)
    {
        if (!auth()->check()) {
            return redirect('/login');
        }
        View::assign([
            'article'    => Article::find($id),
            'categories' => ArticleCategory::categories(false),
            //'comments'   => Comment::
        ]);
        return View::fetch('forum/form');
    }
}
